package com.fjwt.gz.coupon.yspay.yspayutil;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.coupon.yspay.YspayIsvParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
public class YsUtils {

    /**
     * 加密key获取
     **/
    public static String getKey(YspayIsvParams isvParams) {
        /** 2、生成对业务参数加密的密钥*/
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            sb.append(isvParams.getAllChar().charAt(random.nextInt(isvParams.getAllChar().length())));
        }
        String key = ByteUtil.toHexString(sb.toString());

        return key;
    }

    /**
     * 发送http请求获取返回结果，请求地址以文档为准
     *
     * @param isvParams
     * @param reqMap
     * @param key
     * @return
     * @throws Exception
     */
    public static Map<String, String> http(YspayIsvParams isvParams, Map<String, String> reqMap, String key, String HTTP_URL,JSONObject authConfig) throws Exception {

        Map<String, String> resMap = new HashMap<>();
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20 * 1000);
            log.debug("{},http请求返回的原始结果为:{}",HTTP_URL,result);

            byte[] res = Base64.decodeBase64(result);
            resMap = (Map<String, String>) JSONObject.parseObject(new String(res, StandardCharsets.UTF_8), Map.class);
            log.debug("{},请求返回的结果为:{}",HTTP_URL,JSONObject.toJSONString(resMap));

            /** 8、对结果进行解密，并使用银盛公钥验签*/
            if (StringUtils.isNotBlank(resMap.get("sign"))) {
                byte[] srcData = SignUtil.getSignDataStr1(resMap).getBytes("UTF-8");



                log.debug("http请求开始验证签名:YsPublicCer:{}" + isvParams.getYsPublicCer());

                boolean validateSignResult = RSA256Util.validateSign(authConfig.getString("certFilePath"), Base64.decodeBase64(resMap.get("sign")), srcData);
                if (!validateSignResult) {
                    throw new Exception("验签失败");
                }
            } else {
                throw new Exception("验签失败,未返回加签信息,可能是银盛未配置发起方或者发起方证书类型配置有误,返回结果提示为:{}" + resMap.get("msg"));
            }

            /** 9、针对自己的业务，根据返回的结果的code 和 subCode 做接入方的业务处理*/


            /** 10、使用上面生成的加密密钥key，解密返回的业务参数*/
            if (StringUtils.isNotBlank(resMap.get("businessData"))) {
                byte[] data_ = Base64.decodeBase64(resMap.get("businessData"));
                byte[] data = AESUtil.decrypt(data_, ByteUtil.hexStringToBytes(key));
                resMap.put("businessData", new String(data, "UTF-8"));
                log.debug("解密后的业务参数:" + new String(data, "UTF-8"));
            }
            log.debug("解密后的完整参数为:" + JSONObject.toJSONString(resMap));

            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("商户入网申请失败:" + e.getMessage());
        }
        return null;
    }

    public static Map<String, String> httpToGetFilePath(Map<String, String> reqMap,  String HTTP_URL) {

        Map<String, String> resMap ;
        try {
            String result = HttpRequestUtil.getDoPostResponse(HTTP_URL, reqMap, "UTF-8", null, 20 * 1000);
            log.debug("http请求返回的原始结果为:" + result);


            resMap = (Map<String, String>)JSON.parse(result);
            return resMap ;
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("对账单文件下载地址获取失败:" + e.getMessage());
        }
        return null;
    }








}
